﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
using System.IO;

namespace WebAddressBook
{
    public partial class ManageContact : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                InitDDLEnterpriseForSearch();
                InitDDLDeptForSearch();
                //InitGVContactList("");
                ChangeInfoDiv.Visible = false;
            }
        }

        protected void BtChange_Click(object sender, EventArgs e)
        {
            if (!VerifyInpt())
            {
                LbMessage.Text = "<div class='box box-error'>修改失败，带 * 字段不能为空！</div>";
                return;
            }

            Adrr.Model.Base_Employee baseEmployeeModel = new Adrr.Model.Base_Employee();
            Adrr.BLL.Base_Employee baseEmployeeBll = new Adrr.BLL.Base_Employee();

            baseEmployeeModel.EmployID = new Guid(LbEmployeeID.Value);
            baseEmployeeModel.FstName = firstname.Value.Trim();
            baseEmployeeModel.SecName = lastname.Value.Trim();
            baseEmployeeModel.Sex = Convert.ToBoolean(RBsex.SelectedValue);
            baseEmployeeModel.Phone = phone.Value.Trim();
            baseEmployeeModel.Tel = tel.Value.Trim();
            baseEmployeeModel.FamiryTel = famirytel.Value.Trim();
            baseEmployeeModel.Fax = fax.Value.Trim();
            baseEmployeeModel.Email = email.Value.Trim();
            baseEmployeeModel.Station = station.Value.Trim();
            baseEmployeeModel.Address = address.Value.Trim();
            baseEmployeeModel.DeptID = DDLDept.SelectedValue == "" ? DDLEnterprise.SelectedValue : DDLDept.SelectedValue;
            baseEmployeeModel.UpdateTime = DateTime.Now;
            baseEmployeeModel.FromServices = CommonHelper.DataServerUrl;

            if (baseEmployeeBll.Update(baseEmployeeModel))
            {
                LbMessage.Text = "<div class='box box-info'>修改成功！</div>";
                InitGVContactList(GetSearchString());
            }
            else
                LbMessage.Text = "<div class='box box-error'>修改失败！</div>";

        }

        private void InitGVContactList(string strWhere)
        {
            Adrr.BLL.Base_Employee baseEmployee = new Adrr.BLL.Base_Employee();
            //DataSet ds= baseEmployee.GetList("isDelete='false'");
            DataSet ds = baseEmployee.GetListJoinDept(strWhere);
            GVContactList.DataSource = ds;
            GVContactList.DataKeyNames = new string[] { "EmployID" };
            GVContactList.DataBind();
        }

        private void InitDDLEnterprise(string enterpriseId)
        {
            DataSet ds = CommonHelper.GetEnterprise();
            DDLEnterprise.DataSource = ds;
            DDLEnterprise.DataTextField = "DeptName";
            DDLEnterprise.DataValueField = "DeptID";
            DDLEnterprise.DataBind();
            DDLEnterprise.SelectedValue = enterpriseId;
        }

        private void InitDDLDept(string deptId)
        {
            string enterpriseId = DDLEnterprise.SelectedValue;
            //DataSet ds = CommonHelper.GetDept(enterpriseId);
            DataTable dt = CommonHelper.GetDeptList(enterpriseId);
            DDLDept.DataSource = dt;
            DDLDept.DataTextField = "DeptName";
            DDLDept.DataValueField = "DeptID";
            DDLDept.DataBind();
            DDLDept.SelectedValue = deptId;
        }

        private void InitDDLEnterpriseForSearch()
        {
            DataSet ds = CommonHelper.GetEnterprise();
            DDLEnterpriseForSearch.DataSource = ds;
            DDLEnterpriseForSearch.DataTextField = "DeptName";
            DDLEnterpriseForSearch.DataValueField = "DeptID";
            DDLEnterpriseForSearch.DataBind();
        }

        private void InitDDLDeptForSearch()
        {
            string enterpriseId = DDLEnterpriseForSearch.SelectedValue;
            //DataSet ds = CommonHelper.GetDept(enterpriseId);
            DataTable dt = CommonHelper.GetDeptList(enterpriseId);
            DDLDeptmentForSearch.DataSource = dt;
            DDLDeptmentForSearch.DataTextField = "DeptName";
            DDLDeptmentForSearch.DataValueField = "DeptID";
            DDLDeptmentForSearch.DataBind();
            //
            DDLDeptmentForSearch.Items.Add(new ListItem("全部", ""));
            DDLDeptmentForSearch.SelectedValue = "";
        }
        /// <summary>
        /// 查询
        /// </summary>
        protected void BtSearch_Click(object sender, EventArgs e)
        {
            InitGVContactList(GetSearchString());
        }
        /// <summary>
        /// 获取查询的where语句
        /// </summary>
        private string GetSearchString()
        {
            string enterpriseId = DDLEnterpriseForSearch.SelectedValue;
            string deptId = DDLDeptmentForSearch.SelectedValue;
            string name = nameForSearch.Value.Trim();
            StringBuilder strWhere = new StringBuilder();
            if (!string.IsNullOrEmpty(deptId) && !string.IsNullOrEmpty(name))
            {
                strWhere.Append("Base_Employee.DeptID like'" + deptId + "%'");
                strWhere.Append(" and FstName+SecName like '%" + name + "%'");
            }
            else
            {
                if (!string.IsNullOrEmpty(deptId))
                    strWhere.Append("Base_Employee.DeptID like'" + deptId + "%'");
                else
                    strWhere.Append("Base_Employee.DeptID like'" + enterpriseId + "%'");

                if (!string.IsNullOrEmpty(name))
                    strWhere.Append(" and FstName+SecName like '%" + name + "%'");
            }
            return strWhere.ToString();
        }

        protected void DDLEnterpriseForSearch_SelectedIndexChanged(object sender, EventArgs e)
        {
            InitDDLDeptForSearch();
        }

        protected void GVContactList_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
        {
            //显示出进行修改的域
            ChangeInfoDiv.Visible = true;

            //选中要进行修改的记录
            string employId = GVContactList.DataKeys[e.NewSelectedIndex].Value.ToString();

            Adrr.Model.Base_Employee baseEmployeeModel = new Adrr.Model.Base_Employee();
            Adrr.BLL.Base_Employee baseEmployeeBll = new Adrr.BLL.Base_Employee();

            baseEmployeeModel = baseEmployeeBll.GetModel(new Guid(employId));

            //把查询到的数据显示出来
            LbEmployeeID.Value = baseEmployeeModel.EmployID.ToString();
            firstname.Value = baseEmployeeModel.FstName;
            lastname.Value = baseEmployeeModel.SecName;
            RBsex.SelectedIndex = baseEmployeeModel.Sex.ToString() == "True" ? 0 : 1;
            phone.Value = baseEmployeeModel.Phone;
            tel.Value = baseEmployeeModel.Tel;
            famirytel.Value = baseEmployeeModel.FamiryTel;
            fax.Value = baseEmployeeModel.Fax;
            email.Value = baseEmployeeModel.Email;
            station.Value = baseEmployeeModel.Station;
            address.Value = baseEmployeeModel.Address;

            string deptId = baseEmployeeModel.DeptID;
            string enterpirseId = deptId.Substring(0, 4);//前面四位表示该部门是在哪个企业下面的
            InitDDLEnterprise(enterpirseId);
            InitDDLDept(deptId);
        }

        protected void GVContactList_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            string employId = GVContactList.DataKeys[e.RowIndex].Value.ToString();
            Adrr.BLL.Base_Employee baseEmployeeBll = new Adrr.BLL.Base_Employee();
            baseEmployeeBll.SetThisEmployeeIsDeleted(new Guid(employId));

            //刷新数据
            InitGVContactList(GetSearchString());
        }

        protected void GVContactList_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)
                {
                    ((LinkButton)e.Row.Cells[11].Controls[0]).Attributes.Add("onclick", "javascript:return confirm('你确认要删除该联系人：\"" + e.Row.Cells[0].Text.ToUpper() + "\"吗?')");
                }
            }
        }

        private bool VerifyInpt()
        {
            if (string.IsNullOrEmpty(firstname.Value.Trim()) || string.IsNullOrEmpty(lastname.Value.Trim())
                || string.IsNullOrEmpty(phone.Value.Trim()))
                return false;
            else return true;
        }

        protected void BtExport_Click(object sender, EventArgs e)
        {
            Adrr.BLL.Base_Employee baseEmployee = new Adrr.BLL.Base_Employee();
            DataSet ds = baseEmployee.GetDataForOutPut(GetSearchString());
            string outExcelName = DDLEnterpriseForSearch.SelectedItem.Text + "_" + DDLDeptmentForSearch.SelectedItem.Text;
            ExportDsToXls(this.Page, outExcelName, ds);
        }

        public void ExportDsToXls(Page page, string fileName, DataSet ds)
        {
            page.Response.Clear();
            page.Response.Buffer = true;
            //page.Response.Charset = "GB2312";
            page.Response.Charset = "UTF-8";
            //如果输出中文名乱码的话，可以这样编码 文件名  HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8)
            fileName = HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8);
            page.Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName + System.DateTime.Now.ToString("_yyMMdd_hhmm") + ".xls");
            page.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");//设置输出流为简体中文
            page.Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。
            page.EnableViewState = false;
            page.Response.Write(GetExportString(ds));
            page.Response.End();
        }

        public string GetExportString(DataSet ds)
        {
            StringBuilder data = new StringBuilder();

            foreach (DataTable tb in ds.Tables)//多个表
            {
                data.Append("<table cellspacing=\"0\" cellpadding=\"5\" rules=\"all\" border=\"1\">");
                //写出列名
                data.Append("<tr style=\"font-weight: bold; white-space: nowrap;\">");
                foreach (DataColumn column in tb.Columns)
                {
                    data.Append("<td>");
                    data.Append(GetColumnName(column.ColumnName));
                    data.Append("</td>");
                }
                data.Append("</tr>");

                //写出数据
                foreach (DataRow row in tb.Rows)
                {
                    data.Append("<tr>");
                    foreach (DataColumn column in tb.Columns)
                    {
                        if (column.ColumnName.Equals("Sex"))
                        {
                            data.Append("<td>");
                            data.Append(Convert.ToBoolean(row[column].ToString()) ? "男" : "女");
                            data.Append("</td>");
                        }
                        else
                        {
                            data.Append("<td>");
                            data.Append(row[column].ToString());
                            data.Append("</td>");
                        }
                    }
                    data.Append("</tr>");
                }
                data.Append("</table>");
            }
            return data.ToString();
        }

        private string GetColumnName(string columnName)
        {
            switch (columnName)
            {
                case "Name":
                    return "姓名";
                case "Sex":
                    return "性别";
                case "Station":
                    return "职位";
                case "DeptName":
                    return "部门";
                case "Phone":
                    return "手机号码";
                case "Tel":
                    return "办公座机";
                case "FamiryTel":
                    return "家庭电话";
                case "Email":
                    return "Email";
                case "Fax":
                    return "传真";
                case "Address":
                    return "地址";
                default:
                    return "其他";
            }

        }

        #region 另外一种导出方法 现在不用这种方法
        //private void Export(string FileType, string FileName)
        //{
        //    Response.Charset = "UTF8";
        //    Response.ContentEncoding = System.Text.Encoding.UTF8;
        //    Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());
        //    Response.ContentType = FileType;
        //    this.EnableViewState = false;
        //    StringWriter tw = new StringWriter();
        //    HtmlTextWriter hw = new HtmlTextWriter(tw);
        //    GVContactList.RenderControl(hw);
        //    Response.Write(tw.ToString());
        //    Response.End();
        //}

        ////如果没有下面方法会报错类型“GridView”的控件“GridView1”必须放在具有 runat=server 的窗体标记内
        //public override void VerifyRenderingInServerForm(Control control)
        //{

        //}
        #endregion
    }
}